from inventory.models import Item,Location

#search functions
def get_field_value(obj, field):
	#map the form field name to an actual model attribute, location handled separately
	prop_key = {'CAS': 'cas_num', 'NAME':'name', 'MOLFORM' : 'mol_formula', 'SUP': 'supplier'}
	if (field == "LOC"):
		return obj.location.coded_name
	else:
		if field not in prop_key:
			raise Exception('invalid comparison field passed')
		return obj.__dict__[prop_key[field]]

#search cont
def compare_field(obj, field, comp, value):
	val = get_field_value(obj, field)
	if comp == 'IS':
		return val.lower()==value.lower()
	elif comp == 'CONTAINS':
		return val.lower().find(value.lower()) != -1
	elif comp == 'STARTSWITH':
		return val.lower().startswith(value.lower())
	elif comp == 'ENDSWITH':
		return value.lower().endswith(value.lower())
	else:
		raise Exception('invalid comparator passed')
	
#search cont
def search_query(field, compare, value):
	results = []
	q = Item.objects.all()
	for obj in q:
		if compare_field(obj, field, compare, value):
			results.append(obj)
	return results
	
def get_classifications(location):
	result = set()
	objs = Item.objects.filter(location__coded_name__iexact=location)
	
	for o in objs:
		result.add("'%s'" % o.classification)

def delete_items_worker(items):
	for item in items:
		Item.objects.get(id=item).delete()

def move_items_worker(items, location):
	for item in items:
		obj = Item.objects.get(id=item)
		obj.location = location
		obj.save()